package com.major.crowd.filter;

import com.major.crowd.constant.AccessResources;
import com.major.crowd.constant.CrowdConstant;
import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

@Component
public class CrowdAccessFilter extends ZuulFilter {

    Logger logger = LoggerFactory.getLogger(CrowdAccessFilter.class);

    public String filterType() {
        // 这里返回“pre” 意思是在目标微服务前执行过滤
        return "pre";
    }

    public int filterOrder() {
        return 0;
    }

    /**
     * 返回 true，调 run()
     */
    public boolean shouldFilter() {

        logger.info("过滤方法执行=====================");

        // 获取RequestContext对象
        RequestContext requestContext = RequestContext.getCurrentContext();
        // 通过RequestContext获取当前请求对象(底层是ThreadLocal)
        HttpServletRequest request = requestContext.getRequest();
        // 获取servletPath
        String servletPath = request.getServletPath();

        //判断当前路径是否放行
        boolean isContains = AccessResources.PASS_RES_SET.contains(servletPath);
        if (isContains){
            return false;                    //放行，不过滤
        }

        // 判断是否为静态资源
        boolean isStaticResource = AccessResources.isServletPathStaticResource(servletPath);
        /*if (isStaticResource) return false;       //是静态资源，放行
        return true;*/
        return !isStaticResource;
    }

    public Object run() throws ZuulException {
        // 获取 request
        RequestContext requestContext = RequestContext.getCurrentContext();
        HttpServletRequest request = requestContext.getRequest();

        // 获取session
        HttpSession session = request.getSession();
        // 获取已登录用户
        Object loginMember = session.getAttribute(CrowdConstant.ATTR_NAME_LOGIN_MEMBER);

        // 判断是否为空
        if (loginMember == null){
            // 获取response
            HttpServletResponse response = requestContext.getResponse();
            // 提示消息
            session.setAttribute(CrowdConstant.ATTR_NAME_MESSAGE,CrowdConstant.MESSAGE_LOGIN_FORBIDDEN);
            // 重定向到登录页面
            try {
                //response.sendRedirect("http://localhost/auth/member/to/login/page");//http://127.0.0.1/auth/member/to/login/page
                response.sendRedirect("/auth/member/to/login/page");
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        return null;
    }
}
